package org.snusmumr.android.media.util;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Formatter;
import java.util.List;

import android.content.res.Resources;
import android.widget.CursorAdapter;

public class Utils {
	private static final DateFormat iso8601Format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	public static final boolean isEmpty(CharSequence s) {
		return s == null || "".equals(s.toString().trim());
	}
	
	public static final void closeCursor(CursorAdapter adapter) {
		if(adapter != null && 
				adapter.getCursor() != null && 
				!adapter.getCursor().isClosed())
			adapter.getCursor().close();
	}
	
	public static final String format(String format, Object...args ) {
		return new Formatter().format(format, args).toString();
	}
	
	public static final String format(Resources res, int id, Object...args ) {
		return new Formatter().format(res.getString(id), args).toString();
	}
	
	/**
	 * Get selected bits as String divided by ','
	 * @param bitMask
	 * @return
	 */
	public static final String getBitsAsString(String bitMask) {
		List<Integer> array = Bits.getBits(bitMask);
		return getAsString(array);
	}

	public static String getAsString(Iterable<?> collection) {
		StringBuilder buf = new StringBuilder();
		for(Object obj: collection) {
			if(buf.length() > 0)
				buf.append(',');
			buf.append(obj);
		}
		return buf.toString();
	}
	
	public static final Date getDateFromDB(String dbDate) throws ParseException {
		if(isEmpty(dbDate))
			return null;
		return iso8601Format.parse(dbDate);
	}
	
	public static final String getDateAsStringForDB(Date date) {
		if(date == null)
			return null;
		return iso8601Format.format(date);
	}
	
	public static final String arrayToString(long[] array) {
		if(array != null) {
			StringBuilder buf = new StringBuilder();
			for(int i=0; i<array.length; i++) {
				if(i != 0)
					buf.append(", ");
				buf.append(array[i]);
			}
			return buf.toString();
		}
		return null;
	}
	
	public static void releaseList(List<?> list) {
		if(list != null) {
			list.clear();
			list = null;
		}
	}
}
